<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>麦克风SDK - 语音识别示例</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            line-height: 1.6;
        }
        h1, h2 {
            color: #333;
        }
        .container {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        .control-panel {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 20px;
        }
        button {
            padding: 8px 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        button:hover {
            background-color: #45a049;
        }
        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        select, input {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .status {
            padding: 10px;
            background-color: #f5f5f5;
            border-radius: 4px;
            margin-bottom: 10px;
        }
        .visualization {
            height: 100px;
            background-color: #f0f0f0;
            margin-bottom: 20px;
            position: relative;
            border-radius: 4px;
            overflow: hidden;
        }
        .level-bar {
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            background-color: #4CAF50;
            transition: height 0.1s ease;
        }
        .recognition-result {
            min-height: 100px;
            max-height: 300px;
            overflow-y: auto;
            padding: 10px;
            background-color: #f9f9f9;
            border: 1px solid #ddd;
            border-radius: 4px;
            white-space: pre-wrap;
        }
        .interim {
            color: #888;
            font-style: italic;
        }
        .final {
            color: #333;
            font-weight: bold;
        }
        .config-panel {
            background-color: #f5f5f5;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 20px;
        }
        .config-row {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }
        .config-row label {
            width: 150px;
            font-weight: bold;
        }
        .error {
            color: #ff0000;
            font-weight: bold;
        }
        .info {
            margin-top: 20px;
            padding: 10px;
            background-color: #e7f3fe;
            border-left: 6px solid #2196F3;
        }
        .code {
            background-color: #f8f8f8;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 10px;
            font-family: Consolas, Monaco, 'Andale Mono', monospace;
            overflow-x: auto;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <h1>麦克风SDK - 语音识别示例</h1>
    
    <div class="container">
        <div class="status" id="status">状态: 初始化中...</div>
        
        <div class="control-panel">
            <button id="startBtn" disabled>开始录音</button>
            <button id="stopBtn" disabled>停止录音</button>
            <select id="micSelect" disabled>
                <option value="">选择麦克风...</option>
            </select>
            <label for="gainRange">增益: </label>
            <input type="range" id="gainRange" min="0" max="100" value="100" disabled>
        </div>
        
        <div class="config-panel">
            <h3>语音识别配置</h3>
            <div class="config-row">
                <label for="langSelect">识别语言:</label>
                <select id="langSelect">
                    <option value="zh-CN" selected>中文 (zh-CN)</option>
                    <option value="en-US">英语 (en-US)</option>
                    <option value="ja-JP">日语 (ja-JP)</option>
                </select>
            </div>
            <div class="config-row">
                <label for="continuousCheck">连续识别:</label>
                <input type="checkbox" id="continuousCheck" checked>
            </div>
            <div class="config-row">
                <label for="interimCheck">中间结果:</label>
                <input type="checkbox" id="interimCheck" checked>
            </div>
            <div class="config-row">
                <label for="sampleRateSelect">采样率:</label>
                <select id="sampleRateSelect">
                    <option value="16000">16000 Hz (推荐)</option>
                    <option value="44100">44100 Hz</option>
                    <option value="48000">48000 Hz</option>
                </select>
            </div>
        </div>
        
        <h2>音频可视化</h2>
        <div class="visualization">
            <div class="level-bar" id="levelBar" style="height: 0%;"></div>
        </div>
        
        <h2>识别结果</h2>
        <div class="recognition-result" id="recognitionResult"></div>
        
        <div class="info">
            <h3>关于语音识别</h3>
            <p>本示例使用Web Speech API进行语音识别。该API在不同浏览器中的支持程度不同，目前Chrome浏览器支持最好。</p>
            <p>麦克风SDK提供了实时音频流访问功能，可以与任何语音识别服务集成。</p>
        </div>
        
        <div class="code">
            <h3>代码示例</h3>
            <pre>
// 注册音频数据回调
sdk.registerAudioDataCallback((audioData) => {
  // 处理音频数据
  // audioData包含：channelData, sampleRate, timestamp
  
  // 可以将数据发送给自定义语音识别服务
  // sendToSpeechRecognitionService(audioData);
});

// 设置适合语音识别的音频处理配置
sdk.setAudioProcessingConfig({
  enableProcessing: true,
  sampleRate: 16000, // 大多数语音识别服务使用16kHz采样率
  bufferSize: 4096,
  channelCount: 1 // 单声道更适合语音识别
});</pre>
        </div>
    </div>

    <script src="../MicrophoneSDK.js"></script>
    <script>
        // 初始化变量
        let sdk;
        let recognition;
        let isRecognizing = false;
        let finalTranscript = '';
        let interimTranscript = '';
        
        // DOM元素
        const startBtn = document.getElementById('startBtn');
        const stopBtn = document.getElementById('stopBtn');
        const micSelect = document.getElementById('micSelect');
        const gainRange = document.getElementById('gainRange');
        const statusEl = document.getElementById('status');
        const levelBar = document.getElementById('levelBar');
        const recognitionResult = document.getElementById('recognitionResult');
        const langSelect = document.getElementById('langSelect');
        const continuousCheck = document.getElementById('continuousCheck');
        const interimCheck = document.getElementById('interimCheck');
        const sampleRateSelect = document.getElementById('sampleRateSelect');
        
        // 初始化SDK
        async function initSDK() {
            try {
                sdk = new MicrophoneSDK();
                updateStatus('正在初始化SDK...');
                
                const result = await sdk.initialize();
                if (!result) {
                    throw new Error('SDK初始化失败');
                }
                
                // 设置事件监听
                document.addEventListener('audioLevelChange', handleAudioLevelChange);
                document.addEventListener('microphoneStatusChange', handleMicStatusChange);
                document.addEventListener('microphoneError', handleMicError);
                
                // 刷新麦克风列表
                await refreshMicrophoneList();
                
                // 设置音频处理配置
                updateAudioProcessingConfig();
                
                // 启用控件
                startBtn.disabled = false;
                micSelect.disabled = false;
                gainRange.disabled = false;
                
                updateStatus('SDK初始化完成，可以开始录音');
                
                // 初始化语音识别
                initSpeechRecognition();
            } catch (error) {
                updateStatus(`错误: ${error.message}`, true);
                console.error('SDK初始化错误:', error);
            }
        }
        
        // 初始化语音识别
        function initSpeechRecognition() {
            if (!('SpeechRecognition' in window || 'webkitSpeechRecognition' in window)) {
                updateStatus('您的浏览器不支持语音识别API', true);
                return;
            }
            
            const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
            recognition = new SpeechRecognition();
            
            // 设置语音识别参数
            updateRecognitionConfig();
            
            // 设置事件处理
            recognition.onstart = function() {
                isRecognizing = true;
                updateStatus('语音识别已启动');
            };
            
            recognition.onresult = function(event) {
                interimTranscript = '';
                
                for (let i = event.resultIndex; i < event.results.length; ++i) {
                    if (event.results[i].isFinal) {
                        finalTranscript += event.results[i][0].transcript;
                    } else {
                        interimTranscript += event.results[i][0].transcript;
                    }
                }
                
                updateRecognitionResult();
            };
            
            recognition.onerror = function(event) {
                console.error('语音识别错误:', event.error);
                if (event.error === 'no-speech') {
                    updateStatus('未检测到语音', true);
                } else if (event.error === 'audio-capture') {
                    updateStatus('无法捕获音频', true);
                } else if (event.error === 'not-allowed') {
                    updateStatus('语音识别权限被拒绝', true);
                } else {
                    updateStatus(`语音识别错误: ${event.error}`, true);
                }
            };
            
            recognition.onend = function() {
                isRecognizing = false;
                
                // 如果设置为连续识别且麦克风仍在录音，则重新开始识别
                if (continuousCheck.checked && sdk.getMicrophoneStatus() === 'active') {
                    recognition.start();
                } else {
                    updateStatus('语音识别已停止');
                }
            };
        }
        
        // 更新语音识别配置
        function updateRecognitionConfig() {
            if (!recognition) return;
            
            recognition.lang = langSelect.value;
            recognition.continuous = continuousCheck.checked;
            recognition.interimResults = interimCheck.checked;
        }
        
        // 更新音频处理配置
        function updateAudioProcessingConfig() {
            if (!sdk) return;
            
            const sampleRate = parseInt(sampleRateSelect.value, 10);
            
            sdk.setAudioProcessingConfig({
                enableProcessing: true,
                sampleRate: sampleRate,
                bufferSize: 4096,
                channelCount: 1 // 单声道更适合语音识别
            });
        }
        
        // 刷新麦克风列表
        async function refreshMicrophoneList() {
            try {
                const devices = await sdk.refreshMicrophoneList();
                
                // 清空下拉列表
                micSelect.innerHTML = '';
                
                // 添加设备到下拉列表
                devices.forEach(device => {
                    const option = document.createElement('option');
                    option.value = device.deviceId;
                    option.text = device.label || `麦克风 ${device.deviceId.slice(0, 5)}...`;
                    micSelect.appendChild(option);
                });
                
                if (devices.length > 0) {
                    micSelect.value = devices[0].deviceId;
                }
            } catch (error) {
                console.error('获取麦克风列表失败:', error);
                updateStatus('获取麦克风列表失败', true);
            }
        }
        
        // 开始录音
        async function startRecording() {
            try {
                updateStatus('正在启动麦克风...');
                
                // 如果选择了特定麦克风，则使用该麦克风
                if (micSelect.value) {
                    await sdk.selectMicrophone(micSelect.value);
                }
                
                // 设置增益
                const gain = gainRange.value / 100;
                sdk.setGain(gain);
                
                // 开始监听
                const result = await sdk.startListening();
                if (!result) {
                    throw new Error('启动麦克风失败');
                }
                
                // 更新UI
                startBtn.disabled = true;
                stopBtn.disabled = false;
                
                // 开始语音识别
                if (recognition && !isRecognizing) {
                    // 更新配置
                    updateRecognitionConfig();
                    // 清空之前的结果
                    finalTranscript = '';
                    interimTranscript = '';
                    updateRecognitionResult();
                    // 开始识别
                    recognition.start();
                }
                
                updateStatus('麦克风已启动，正在录音...');
            } catch (error) {
                updateStatus(`错误: ${error.message}`, true);
                console.error('启动麦克风错误:', error);
            }
        }
        
        // 停止录音
        async function stopRecording() {
            try {
                updateStatus('正在停止麦克风...');
                
                // 停止监听
                const result = await sdk.stopListening();
                if (!result) {
                    throw new Error('停止麦克风失败');
                }
                
                // 更新UI
                startBtn.disabled = false;
                stopBtn.disabled = true;
                
                // 停止语音识别
                if (recognition && isRecognizing) {
                    recognition.stop();
                }
                
                updateStatus('麦克风已停止');
            } catch (error) {
                updateStatus(`错误: ${error.message}`, true);
                console.error('停止麦克风错误:', error);
            }
        }
        
        // 处理音频电平变化
        function handleAudioLevelChange(event) {
            const level = event.detail.level;
            levelBar.style.height = `${level * 100}%`;
        }
        
        // 处理麦克风状态变化
        function handleMicStatusChange(event) {
            const status = event.detail.status;
            if (status === 'active') {
                updateStatus('麦克风已启动，正在录音...');
                startBtn.disabled = true;
                stopBtn.disabled = false;
            } else {
                updateStatus('麦克风已停止');
                startBtn.disabled = false;
                stopBtn.disabled = true;
                // 重置音量条
                levelBar.style.height = '0%';
            }
        }
        
        // 处理麦克风错误
        function handleMicError(event) {
            const error = event.detail.error;
            updateStatus(`麦克风错误: ${error}`, true);
            console.error('麦克风错误:', error);
            
            // 重置UI
            startBtn.disabled = false;
            stopBtn.disabled = true;
        }
        
        // 更新状态显示
        function updateStatus(message, isError = false) {
            statusEl.textContent = `状态: ${message}`;
            if (isError) {
                statusEl.classList.add('error');
            } else {
                statusEl.classList.remove('error');
            }
        }
        
        // 更新识别结果显示
        function updateRecognitionResult() {
            recognitionResult.innerHTML = '';
            
            if (finalTranscript) {
                const finalSpan = document.createElement('div');
                finalSpan.className = 'final';
                finalSpan.textContent = finalTranscript;
                recognitionResult.appendChild(finalSpan);
            }
            
            if (interimTranscript) {
                const interimSpan = document.createElement('div');
                interimSpan.className = 'interim';
                interimSpan.textContent = interimTranscript;
                recognitionResult.appendChild(interimSpan);
            }
            
            // 滚动到底部
            recognitionResult.scrollTop = recognitionResult.scrollHeight;
        }
        
        // 事件监听
        document.addEventListener('DOMContentLoaded', initSDK);
        startBtn.addEventListener('click', startRecording);
        stopBtn.addEventListener('click', stopRecording);
        gainRange.addEventListener('input', () => {
            if (sdk) {
                const gain = gainRange.value / 100;
                sdk.setGain(gain);
            }
        });
        
        // 配置变更监听
        langSelect.addEventListener('change', updateRecognitionConfig);
        continuousCheck.addEventListener('change', updateRecognitionConfig);
        interimCheck.addEventListener('change', updateRecognitionConfig);
        sampleRateSelect.addEventListener('change', updateAudioProcessingConfig);
        
        // 页面卸载时清理资源
        window.addEventListener('beforeunload', () => {
            if (sdk) {
                sdk.dispose();
            }
            if (recognition && isRecognizing) {
                recognition.stop();
            }
        });
    </script>
</body>
</html>